import { _decorator, Component, Node, JsonAsset, TextAsset, Label, resources, Sprite, SpriteFrame, Prefab, instantiate, RichText, input, Input, Button, find } from 'cc';
import { rewardBox } from './rewardBox';

const { ccclass, property } = _decorator;

@ccclass('storyView')
export class storyView extends Component {

    jsonData;

    /**
     * 当前对话id
     */
    DialogueID: number = 0;

    /**聊天box */
    @property(Node)
    nameBox: Node;

    /**场景box */
    @property(Node)
    SceneBox: Node;

    /**人物box */
    @property(Node)
    FigureBox: Node;

    /**聊天框*/
    @property(RichText)
    ChatBox: RichText;

    /**打字机 定时器ID*/
    printerTimer: number;

    /**继续 聊天按钮 */
    @property(Node)
    btn: Node;

    /** 菜单box */
    @property(Node)
    MenuBox: Node;

    /** 菜单Item */
    @property(Prefab)
    MenuItem: Prefab;

    /** 战斗界面 */
    @property(Prefab)
    fightView: Prefab;

    /** 奖励界面 */
    @property(Prefab)
    rewardView: Prefab;

    /**过滤后的json */
    private item: any
    private fight: Node = null



    onLoad() {

    }

    start() {
        this.ChatBox.node.parent.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
    }

    init(currentBranch) {
        this.jsonData = currentBranch;
        let condition = { isBegin: "TRUE" }
        const begin = this.queryOneByCondition(this.jsonData, condition);
        if (begin) {
            this.item = begin;
            this.chat();
        } else {
            console.log("Dictionary is empty.");
        }

    }

    /**
     * 根据ID查询一条表内容
     * @param {string}table 表
     * @param {string}ID
     * @returns {Object} 一条表内容
     */
    queryByID(table: any, ID: string, key: string = null) {

        if (!table) {
            return null;
        }

        if (key) {
            for (var tbItem in table) {
                if (!table.hasOwnProperty(tbItem)) {
                    continue;
                }

                if (table[tbItem][key] === ID) {
                    return table[tbItem];
                }
            }
        } else {
            return table[ID];
        }
    }

    queryOneByCondition(table: any, condition: any) {
        if (condition.constructor !== Object) {
            return null;
        }
        if (!table) {
            return null;
        }

        var keys = Object.keys(condition);
        var keysLength = keys.length;

        for (let keyName in table) {
            var item = table[keyName];

            var fit = true;
            for (var j = 0; j < keysLength; j++) {
                var key = keys[j];
                fit = fit && (condition[key] === item[key]);
            }

            if (fit) {
                return item;
            }
        }

        return null;
    }


    update(deltaTime: number) {

    }


    onTouchStart() {
        this.item = this.jsonData[this.DialogueID];
        this.chat();
    }

    /**
     * 聊天
     */
    chat() {
        switch (this.item.sign) {
            case "#": //对话
                this.setChat();
                break;
            case "&": //选择菜单
                this.GenerateSelectionMenu(this.item.ID);
                break;
            case "@": //进入战斗
                this.setFight();
                break;
            case "$": //奖励菜单
                this.setReward();
                break;
            case "END": //结束
                this.scheduleOnce(() => {
                    this.printerTimer && clearInterval(this.printerTimer);
                }, 1)
                this.setEnd();
                break;
        };
    }

    /**
     * 进入战斗
     */
    setFight() {
        this.fight = instantiate(this.fightView);
        this.node.addChild(this.fight);
        this.fight.getChildByName("win_button").on(Button.EventType.CLICK, this.winClick, this);
        this.fight.getChildByName("fail_button").on(Button.EventType.CLICK, this.failClick, this);
    }

    setEnd() {
        let end = this.node.getChildByName("endView")
        end.active = true;
        end.getChildByName("Label").getComponent(Label).string = this.item.content
    }

    setReward() {
        let rewardlist = []
        rewardlist.push(`名声  ${this.item.reputation}`);
        rewardlist.push(`经验值  ${this.item.experience}`);
        rewardlist.push(`金币 ${this.item.goldCoin}`);
        let reward = instantiate(this.rewardView);
        this.node.addChild(reward);
        reward.getComponent(rewardBox).list = rewardlist
        this.DialogueID = this.item.skip;
        this.item = this.jsonData[this.DialogueID];
        this.chat();
    }


    winClick() {
        this.DialogueID = this.item.skip;
        this.item = this.jsonData[this.DialogueID];
        this.fight.destroy();
        this.chat();
    }

    failClick() {
        this.DialogueID = this.item.failSkip;
        this.item = this.jsonData[this.DialogueID];
        this.fight.destroy();
        this.chat();
    }



    /**
     * 背景图片
     * @param item 
     */
    setPic() {

        if (this.item.backPic != null || this.item.backPic != '') {
            let path = 'pic/背景图/' + this.item.backPic + '/spriteFrame'
            resources.load(path, SpriteFrame, (err, spriteFrame) => {
                this.SceneBox.children[0].getComponent(Sprite).spriteFrame = spriteFrame;
            });

        }

    }


    /**
     * 设置聊天
     */
    setChat() {
        this.setPic();
        this.FigureBox.children[0].getComponent(Sprite).spriteFrame = null;
        this.FigureBox.children[1].getComponent(Sprite).spriteFrame = null;
        //位置
        this.nameBox.children.map(e => e.active = false);
        let RealName = "";
        //小于四个字的名字
        if (this.item.role != undefined) {
            RealName = this.item.role
        }
        console.log("this.item.boxPos", this.item.boxPos);

        if (this.item.boxPos == '左') {
            this.nameBox.children[0].active = true;
            this.nameBox.children[0].getChildByName('Label').getComponent(Label).string = RealName;
            this.showRolePainting(0);
        } else if ((this.item.boxPos == '右')) {
            this.nameBox.children[1].active = true;
            this.nameBox.children[1].getChildByName('Label').getComponent(Label).string = RealName;
            this.showRolePainting(1);
        }

        //内容
        this.makeLabelPrinter(this.item.content)


        //下一条Id
        this.DialogueID = this.item.skip;
        // console.log("this.DialogueID", this.DialogueID);



    }

    /**
     * 显示人物立绘
     * @param direction 
     * @returns .id
     */
    showRolePainting(direction) {

        if (this.item.roleID != null || this.item.roleID != '') {
            let path = 'pic/人物图/' + this.item.roleID + '/spriteFrame'
            resources.load(path, SpriteFrame, (err, spriteFrame) => {
                this.FigureBox.children[direction].getComponent(Sprite).spriteFrame = spriteFrame;
            });
        }
    }


    /**
     * 打字机 效果
     */
    makeLabelPrinter(str: string) {
        this.btn.active = false;

        let charArr = str.split('');
        let charIdx = 0;

        this.printerTimer && clearInterval(this.printerTimer);
        this.printerTimer = setInterval(() => {
            if (charIdx >= charArr.length) {
                this.btn.active = true;
                this.printerTimer && clearInterval(this.printerTimer);
            } else {
                charIdx += 1;
                this.ChatBox.string = charArr.slice(0, charIdx).join('');
            }
        }, 100);
    }

    /**
     * 生成选择菜单
     */
    GenerateSelectionMenu(id) {
        if (this.item.sign != "&") return;
        let tempNode = instantiate(this.MenuItem);
        let label = tempNode.getChildByName('Label').getComponent(Label);
        label.string = this.item.content;
        this.MenuBox.active = true;
        this.MenuBox.getChildByName('menu').addChild(tempNode);
        tempNode['tiemData'] = this.item;
        tempNode.on('click', this.MenuClick, this);

        let tempId = Number(this.item.id) + 1

        if (this.jsonData[this.DialogueID].sign == "&") {
            this.DialogueID = tempId;
        } else {
        }
        this.item = this.jsonData[this.DialogueID];

        this.GenerateSelectionMenu(this.DialogueID);

    }

    /**
     * 更新id
     */
    updateItem() {
        this.DialogueID = this.item.skip;
        this.item = this.jsonData[this.DialogueID];
        this.chat();

    }

    /**
     * 菜单点击
     */
    MenuClick(e) {
        let item = e.node['tiemData'];
        this.DialogueID = item.skip;
        this.item = this.jsonData[this.DialogueID];


        // //是否有什么效果
        // if (item.reputation || item.meritoriousService || item.goodAndEvil || item.silverTael || item.goods || item.favorability) {
        //     taskSys.ins.taskCompleted(item);
        //     console.log('效果', item)
        // }

        this.MenuBox.active = false;
        this.MenuBox.getChildByName('menu').removeAllChildren();

        this.chat();
    }




}


